<template>
	<div class="page_account" id="account_register">
		<!-- 背景遮罩 -->
		<div class="register_overlay" @click="closeModal"></div>
		
		<!-- 注册模态框 -->
		<div class="register_modal">
			<div class="register_container">
				<!-- 左侧功能展示区 -->
				<div class="left_sidebar">
					<div class="sidebar_header">
						<div class="logo_area">
							<img src="/img/qrcode_img.png" alt="Logo" class="logo_img" />
						<div class="logo_text">
							<div class="logo_title">{{ t('systemName') }}</div>
							<div class="logo_subtitle">{{ t('systemSubtitle') }}</div>
							<div class="logo_english">Academic Conference System</div>
						</div>
						</div>
					</div>
					<div class="sidebar_content">
						<div class="feature_list">
							<div class="feature_item" v-for="(feature, index) in features" :key="index">
								<i class="el-icon-check feature_icon"></i>
								<span class="feature_text">{{ t(feature) }}</span>
							</div>
						</div>
					</div>
				</div>
				
				<!-- 右侧注册表单区 -->
				<div class="right_content">
					<div class="content_header">
						<h2 class="page_title">{{ t('register') }}</h2>
						<i class="el-icon-close close_btn" @click="closeModal"></i>
					</div>
					
					<!-- 注册方式切换 -->
					<div class="register_tabs">
						<div class="tab_item" :class="{ active: registerType === 'phone' }" @click="registerType = 'phone'">
							{{ t('phoneRegistration') }}
						</div>
						<div class="tab_item" :class="{ active: registerType === 'email' }" @click="registerType = 'email'">
							{{ t('emailRegistration') }}
						</div>
					</div>
					
					<!-- 注册表单 -->
					<div class="register_form">
						<b-form>
							<!-- 手机注册 -->
							<template v-if="registerType === 'phone'">
								<b-form-group :id="'input-group-phone'" :label="t('phoneNumber')" :label-for="'input-phone'">
									<div class="phone_input_group">
										<b-form-select id="country_code" v-model="countryCode" class="country_code_select">
											<b-form-select-option value="+86">中国 +86</b-form-select-option>
											<b-form-select-option value="+1">美国 +1</b-form-select-option>
											<b-form-select-option value="+44">英国 +44</b-form-select-option>
										</b-form-select>
										<b-form-input id="input-phone" v-model="form.phone" type="text" 
											:placeholder="t('enterPhoneNumber')" class="phone_input" trim></b-form-input>
									</div>
								</b-form-group>
							</template>
							
							<!-- 邮箱注册 -->
							<template v-if="registerType === 'email'">
								<b-form-group :id="'input-group-email'" :label="t('emailAddress')" :label-for="'input-email'">
									<b-form-input id="input-email" v-model="form.email" type="email" 
										:placeholder="t('enterEmailAddress')" trim></b-form-input>
								</b-form-group>
							</template>
							
							<!-- 密码 -->
							<b-form-group :id="'input-group-password'" :label="t('password')" :label-for="'input-password'">
								<b-form-input id="input-password" v-model="form.password" type="password" 
									:placeholder="t('enterPassword')" class="password_input" trim></b-form-input>
								<i class="el-icon-view password_toggle" @click="togglePasswordVisibility"></i>
							</b-form-group>
							
							<!-- 验证码 -->
							<b-form-group :id="'input-group-captcha'" :label="t('verificationCode')" :label-for="'input-captcha'">
								<!-- 手机注册：短信验证码 -->
								<template v-if="registerType === 'phone'">
									<div class="captcha_input_group">
										<b-form-input id="input-captcha" v-model="captcha" type="text" 
											:placeholder="t('enterSmsVerificationCode')" class="captcha_input" trim></b-form-input>
										<el-button type="success" class="get_captcha_btn" @click="getCaptcha" :disabled="smsCountdown > 0">
											{{ smsCountdown > 0 ? `${smsCountdown}${t('retryAfterSeconds')}` : t('getSmsCode') }}
										</el-button>
									</div>
								</template>
								<!-- 邮箱注册：图形验证码 -->
								<template v-else>
									<div class="captcha_input_group">
										<b-form-input id="input-captcha-email" v-model="captcha" type="text" 
											:placeholder="t('enterImageVerificationCode')" class="captcha_input" trim></b-form-input>
										<img :src="captchaImageUrl" @click="refreshCaptcha" alt="Captcha" class="captcha-img" :key="captchaRefreshKey">
									</div>
								</template>
							</b-form-group>
							
							<!-- 账号 -->
							<b-form-group :id="'input-group-username'" :label="t('account')" :label-for="'input-username'">
								<b-form-input id="input-username" v-model="form.username" type="text" 
									:placeholder="t('enterAccount')" trim></b-form-input>
							</b-form-group>
							
							<!-- 昵称 -->
							<b-form-group :id="'input-group-nickname'" :label="t('nickname')" :label-for="'input-nickname'">
								<b-form-input id="input-nickname" v-model="form.nickname" type="text" 
									:placeholder="t('enterNickname')" trim></b-form-input>
							</b-form-group>
							
							<!-- 默认设置为普通用户，不需要选择 -->
							
							<!-- 同意协议 -->
							<div class="agreement_checkbox">
								<b-form-checkbox v-model="agreeToTerms">
									{{ t('agreeToTerms') }}
								</b-form-checkbox>
							</div>
							
							<!-- 提交按钮 -->
							<div class="submit_btn_wrap">
								<el-button type="primary" class="submit_btn" @click.stop.prevent="submit()">{{ t('confirm') }}</el-button>
							</div>
							
							<!-- 已有账号链接 -->
							<div class="login_link">
								<span>{{ t('alreadyHaveAccount') }} </span>
								<router-link to="/account/login" class="login_link_text">{{ t('loginNow') }}</router-link>
							</div>
						</b-form>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import mixin from "@/mixins/page.js";
	import form_ordinary_users from "@/components/diy/form_ordinary_users";
	import mixin_i18n from "@/mixins/i18n.js";
	
	export default {
		components: {
			form_ordinary_users,
		},
		mixins: [mixin, mixin_i18n],
		data() {
			return {
				url_submit: "~/api/user/register?",
				registerType: 'phone',
				countryCode: '+86',
				captcha: '',
				captchaRefreshKey: Date.now(),
				smsCountdown: 0,
				agreeToTerms: true,
				showPassword: false,
				features: [
					'academicConference',
					'articleManagement',
					'announcementNews',
					'conferenceRegistration',
					'callForPapersTopics',
					'contactUs',
					'collectionManagement'
				],
				form: {
					username: "",
					password: "",
					nickname: "",
					email: "",
					phone: "",
					user_group: "普通用户" // 默认设置为普通用户
				},
				form_sub: {},
				list_user_group: [],
				user_group: [],
			};
		},
		computed: {
			/**
			 * 获取验证码图片URL
			 */
			captchaImageUrl() {
				return `/api/captcha/get?t=${this.captchaRefreshKey}`;
			}
		},
		methods: {
			closeModal() {
				this.$router.push('/');
			},
			togglePasswordVisibility() {
				this.showPassword = !this.showPassword;
				const input = document.getElementById('input-password');
				if (input) {
					input.type = this.showPassword ? 'text' : 'password';
				}
			},
			/**
			 * 刷新图形验证码
			 */
			refreshCaptcha() {
				this.captchaRefreshKey = Date.now();
				this.captcha = '';
			},
			/**
			 * 获取验证码（短信或图形）
			 */
			getCaptcha() {
				if (this.registerType === 'phone') {
					if (!this.form.phone) {
						this.$message.warning(this.t('enterPhoneNumber'));
						return;
					}
					// 发送短信验证码
					this.$post("~/api/user/send_sms?", { phone: this.form.phone }, (res) => {
						if (res.result) {
							this.$message.success(this.t('verificationCodeSent'));
							// 开始倒计时
							this.smsCountdown = 60;
							const timer = setInterval(() => {
								this.smsCountdown--;
								if (this.smsCountdown <= 0) {
									clearInterval(timer);
								}
							}, 1000);
						} else if (res.error) {
							this.$message.error(res.error.message || '发送失败，请重试');
						}
					});
				} else {
					// 刷新图形验证码
					this.refreshCaptcha();
				}
			},
			get_list_user_group() {
				this.$get("~/api/user_group/get_list?register_max=3&register_min=2", {}, (res) => {
					if (res.result.list) {
						var lt = [];
						var list = res.result.list;
						list = list.filter((x) => x.name !== "专家用户");
						list.map((x) => {
							lt.push({
								"value": x.name,
								"text": x.name
							})
						});
						this.list_user_group = lt;
						this.user_group = list;
					} else if (res.error) {
						console.error(res.error);
						this.$toast(res.error.message,"error");
					}
				})
			},
			async submit(param, func) {
				if (!param) {
					param = this.form;
				}
				if (this.registerType === 'phone') {
					if (!param.phone) {
						this.$toast(this.t('enterPhoneNumber'), 'danger');
						return;
					}
					param.username = param.phone;
				} else if (this.registerType === 'email') {
					if (!param.email) {
						this.$toast(this.t('enterEmailAddress'), 'danger');
						return;
					}
					param.username = param.email;
				}
				
				if (!this.agreeToTerms) {
					this.$toast(this.t('pleaseAgreeToTerms'), 'danger');
					return;
				}
				
				var pm = this.events("submit_before", Object.assign({}, param)) || param;
				console.log("[前端调试] submit_before 执行后的参数:", pm);
				var msg = await this.events("submit_check", pm);
				var ret;
				
				if (msg) {
					this.$toast(msg, 'danger');
				} else {
					console.log("[前端调试] 准备调用 submit_main，参数:", pm);
					ret = this.events("submit_main", pm, func);
				}
				return ret;
			},
			submit_before(param){
				console.log("[前端调试] submit_before 被调用");
				console.log("[前端调试] registerType:", this.registerType);
				console.log("[前端调试] captcha 值:", this.captcha);
				console.log("[前端调试] 原始参数:", JSON.stringify(param));
				
				// 确保 user_group 有默认值
				if (!param.user_group || param.user_group === "") {
					param.user_group = "普通用户";
				}
				// 添加验证码到提交参数
				if(this.registerType === 'phone'){
					param.sms_code = this.captcha;
					console.log("[前端调试] 设置 sms_code:", param.sms_code);
				} else {
					param.captcha = this.captcha;
					param.captcha_id = this.captchaRefreshKey.toString();
					console.log("[前端调试] 设置 captcha:", param.captcha, "captcha_id:", param.captcha_id);
				}
				
				console.log("[前端调试] 修改后的参数:", JSON.stringify(param));
				// 重要：返回修改后的参数
				return param;
			},
			async submit_check(param){
				var ret = null;
				var email_regular = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
				var phone_regular = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
				var {username, password, nickname, user_group, email, phone} = param;
				
				if(!username){
					ret = "账号不能为空";
				}
				else if(username.length > 16 || username.length < 5){
					ret = "账号长度应为5到16个字符之间！";
				}
				else if(!password){
					ret = "密码不能为空!";
				}
				else if(password.length > 16 || password.length < 5){
					ret = "密码长度应为5到16个字符之间！";
				}
				else if(nickname && (nickname.length > 12 || nickname.length < 2)){
					ret = "昵称长度应为2个字符到12个字符之间";
				}
				else if(this.registerType === 'email' && email && !email_regular.test(email)){
					ret = "请输入正确的邮箱地址 例：test@test.com!";
				}
				else if(this.registerType === 'phone' && phone && !phone_regular.test(phone)){
					ret = "请输入正确的手机号码 例：18955552312!";
				}
				else if(!this.captcha){
					ret = "请输入验证码";
				}
				
				// 验证验证码
				if(!ret && this.captcha){
					if(this.registerType === 'phone'){
						// 手机注册：验证短信验证码（在后端验证）
						// 这里只检查是否输入，实际验证在后端
					} else {
						// 邮箱注册：验证图形验证码
						var verifyRes = await this.$post("~/api/captcha/verify?", {
							code: this.captcha,
							captcha_id: this.captchaRefreshKey.toString()
						});
						if(!verifyRes.result){
							ret = verifyRes.message || "验证码错误，请重新输入";
							if(ret.includes("错误") || ret.includes("过期")){
								this.refreshCaptcha();
							}
						}
					}
				}
				
				if(!ret && user_group){
					if(user_group === "普通用户"){
						var form_sub = Object.assign({}, this.form_sub);
					}
				}
				
				var p = {"username": param.username};
				if(!ret){
					var res = await this.$get("~/api/user/count?", p);
					if (res.result) {
						ret = "用户已存在!";
					}
				}
				return ret;
			},
			submit_after(json, func) {
				var form = Object.assign({}, this.form);
				delete form.password;
				// 从user_group数组中查找匹配的用户组
				var userGroupObj = null;
				if (this.user_group && this.user_group.length > 0) {
					userGroupObj = this.user_group.find(function(item) {
						return item.name === form.user_group;
					});
				}
				var table = userGroupObj ? userGroupObj.source_table : null;
				if(table){
					this.get_submit(form, table);
				} else {
					// 如果没有source_table（如普通用户），直接显示成功消息并跳转
					this.$toast(this.t('registrationSuccess'), "success");
					this.$router.push("/");
				}
			},
			get_submit(form, table) {
				var form_sub = this.form_sub;
				this.$get("~/api/user/get_obj?", form, (res) => {
					if (res.result && res.result.obj) {
						form_sub.user_id = res.result.obj.user_id;
						this.submit_sub(form_sub, table);
					} else if (res.error) {
						console.error(res.error);
						this.$toast(res.error.message,"error");
					}
				});
			},
			submit_sub(form, table) {
				this.$post("~/api/" + table +"/add?", form, (res) => {
					if(res.result){
						this.$toast(this.t('registrationSuccess'));
						this.$router.push("/");
					}
					else if(res.error){
						console.error(res.error);
						this.$toast(res.error.message);
					}
				})
			}
		},
		created() {
			this.get_list_user_group();
		}
	};
</script>

<style scoped>
.page_account {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	z-index: 9999;
}

.register_overlay {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, 0.5);
	backdrop-filter: blur(4px);
}

.register_modal {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 90%;
	max-width: 1000px;
	max-height: 90vh;
	background: #fff;
	border-radius: 12px;
	box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
	overflow: hidden;
	display: flex;
	flex-direction: column;
}

.register_container {
	display: flex;
	min-height: 600px;
	max-height: 80vh;
	overflow: hidden;
}

/* 左侧功能展示区 */
.left_sidebar {
	width: 40%;
	background: linear-gradient(180deg, #4A90E2 0%, #357ABD 100%);
	display: flex;
	flex-direction: column;
	padding: 40px;
	color: #fff;
	overflow-y: auto;
}

.sidebar_header {
	margin-bottom: 40px;
}

.logo_area {
	display: flex;
	align-items: center;
}

.logo_img {
	width: 50px;
	height: 50px;
	margin-right: 15px;
	border-radius: 8px;
}

.logo_text {
	flex: 1;
}

.logo_title {
	font-size: 24px;
	font-weight: bold;
	margin-bottom: 6px;
}

.logo_subtitle {
	font-size: 14px;
	opacity: 0.9;
	margin-bottom: 4px;
}

.logo_english {
	font-size: 12px;
	opacity: 0.8;
}

.sidebar_content {
	flex: 1;
}

.feature_list {
	display: flex;
	flex-direction: column;
	gap: 16px;
}

.feature_item {
	display: flex;
	align-items: center;
	font-size: 14px;
}

.feature_icon {
	margin-right: 10px;
	font-size: 16px;
	color: #87CEEB;
}

.feature_text {
	flex: 1;
}

/* 右侧注册表单区 */
.right_content {
	width: 60%;
	background: #fff;
	padding: 40px 50px;
	display: flex;
	flex-direction: column;
	overflow-y: auto;
}

.content_header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 30px;
	position: relative;
}

.page_title {
	font-size: 28px;
	font-weight: bold;
	color: #333;
	margin: 0;
	text-align: center;
	width: 100%;
}

.close_btn {
	font-size: 24px;
	cursor: pointer;
	color: #999;
	position: absolute;
	right: 0;
	top: 0;
	transition: color 0.3s;
}

.close_btn:hover {
	color: #333;
}

.register_tabs {
	display: flex;
	margin-bottom: 30px;
	border-bottom: 2px solid #f0f0f0;
	justify-content: center;
}

.tab_item {
	padding: 10px 20px;
	cursor: pointer;
	color: #999;
	font-size: 15px;
	border-bottom: 2px solid transparent;
	margin-bottom: -2px;
	transition: all 0.3s;
}

.tab_item:hover {
	color: #4A90E2;
}

.tab_item.active {
	color: #E6A23C;
	border-bottom-color: #E6A23C;
	font-weight: bold;
}

.register_form {
	flex: 1;
}

.phone_input_group {
	display: flex;
	gap: 10px;
}

.country_code_select {
	width: 130px;
	flex-shrink: 0;
}

.phone_input {
	flex: 1;
}

.password_input {
	position: relative;
}

.password_toggle {
	position: absolute;
	right: 12px;
	top: 50%;
	transform: translateY(-50%);
	cursor: pointer;
	color: #999;
	z-index: 10;
}

.password_toggle:hover {
	color: #333;
}

.captcha_input_group {
	display: flex;
	gap: 10px;
}

.captcha_input {
	flex: 1;
}

.get_captcha_btn {
	flex-shrink: 0;
}

.captcha-img {
	height: 40px;
	cursor: pointer;
	border: 1px solid #dcdfe6;
	border-radius: 4px;
	flex-shrink: 0;
	background-color: #f5f7fa;
	transition: border-color 0.3s;
}

.captcha-img:hover {
	border-color: #409eff;
}

.agreement_checkbox {
	margin: 20px 0;
}

.submit_btn_wrap {
	margin: 30px 0;
}

.submit_btn {
	width: 100%;
	height: 44px;
	font-size: 16px;
}

.login_link {
	text-align: center;
	margin-top: 15px;
	color: #666;
}

.login_link_text {
	color: #4A90E2;
	text-decoration: none;
	cursor: pointer;
}

.login_link_text:hover {
	text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
	.register_modal {
		width: 95%;
		max-width: none;
	}
	
	.register_container {
		flex-direction: column;
		min-height: auto;
	}
	
	.left_sidebar {
		width: 100%;
		min-height: 200px;
		padding: 30px 20px;
	}
	
	.right_content {
		width: 100%;
		padding: 30px 20px;
	}
}
</style>
